package kr.hkit.androidcomplete03.ch26;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class WordDAO {
	private WordDBHelper helper;
	private SQLiteDatabase db;

	public WordDAO(Context context) {
		this.helper = new WordDBHelper(context);
		this.db = helper.getWritableDatabase();
	}

	public static WordDAO open(Context context) {
		return new WordDAO(context);
	}

	public void close() {
		helper.close();
	}

	public boolean insert(String eng, String han) {
		//첫번째 방법
/*		String sql = "insert into dic values (null, '" + eng + "','" + han + "');";

		try {
			db.execSQL(sql);
		} catch (SQLException e) {
			Log.d("WordDao", "insert Error" + e.getMessage());
			return false;
		}

		return true;*/
		
		//두번째 방법
		ContentValues row = new ContentValues();
		row.put("eng", eng);
		row.put("han", han);
		long res = db.insert(EngWord.DB_NAME, null, row);
		if(res == -1){
			return false;
		} else {
			return true;
		}
	}

	public boolean deleteAll() {
		//첫번째 방법
		/*String sql = "delete from dic;";

		try {
			db.execSQL(sql);
		} catch (SQLException e) {
			Log.d("WordDao", "delete Error" + e.getMessage());
			return false;
		}

		return true;*/
		
		//두번째 방법
		db.delete("dic", null, null);
		return true;
	}

	public boolean delete(int id) {
/*		String sql = "delete from dic where _id=" + id + ";";

		try {
			db.execSQL(sql);
		} catch (SQLException e) {
			Log.d("WordDao", "delete Error" + e.getMessage());
			return false;
		}

		return true;*/
		
		//두번째 방법
		String[] args = {String.valueOf(id)};
		db.delete(EngWord.DB_NAME, "_id=?", args);
		return true;
	}

	public Cursor selectAll() {
		String sql = "select * from dic";
		Cursor cursor = db.rawQuery(sql, null);
		if (cursor != null) {
			cursor.moveToFirst();
		}
		return cursor;
	}

	public boolean update(int id, String eng, String han) {
		String sql = "update dic set han = '" + han + "', eng = '" + eng + "' where _id=" + id + ";";

		try {
			db.execSQL(sql);
		} catch (SQLException e) {
			Log.d("WordDao", "update Error" + e.getMessage());
			return false;
		}

		return true;
	}
}
